<?php 

class FRM_ACL
{
	/**
	 * Enter description here...
	 *
	 * @var Zend_Auth
	 */
	public static $currentAuth;
	
	/**
	 * Enter description here...
	 *
	 * @var Zend_Auth
	 */
	public static $currentModule;
	
	/**
	 * Enter description here...
	 *
	 * @var array
	 */
	static protected $access;

	/**
	 * Enter description here...
	 *
	 * @var array
	 */
	static protected $accessList;

	static protected $accessTree;
	
	static public $currentStatus;
	
	protected static function setAccessList(){

		$res = array();
		if(is_null(self::$currentStatus) || self::$currentModule!=='operator'){
			$xml = implode('', file (PATH_BASE."/config/".self::$currentModule."/permissions.xml"));
		}else{
			$xml = implode('', file (PATH_BASE."/config/".self::$currentModule."/permissions".self::$currentStatus.".xml"));
		}
		self::$accessTree = FRM_Tools_Xml::XMLToArray($xml);

		if(!empty(self::$accessTree['children'])){
			self::$accessTree = self::$accessTree['children'];
		}
		$res = FRM_Tools_Array::accessArrayToLinearArray(self::$accessTree);

		self::$accessList = $res;
	}

	public static function getAccessList(){

		if(empty(self::$accessList)){
			self::setAccessList();
		}
		return self::$accessList;
	}

	public static function getAccessTree(){

		if(empty(self::$accessTree)){
			self::setAccessList();
		}
		return self::$accessTree;
	}

	public static function getAccess(){
		if(is_null(self::$access) && !empty(self::$currentAuth)){
			$userData = self::$currentAuth->getStorage()->read();
			if(!empty($userData->permissions) && 0){
				self::$access = $userData->permissions;
			}elseif(isset($userData->id)) {
				$access = new Admin_Access();

				$userData->permissions = $access->getAccess($userData->id);

				self::$access = $userData->permissions;
				self::$currentAuth->getStorage()->write($userData);
			}
		}
		return self::$access;
	}

	public static function hasPermition($controller, $action){

		self::getAccess();
		self::getAccessList();

		//TODO Change it when access will works
		//self::$accessList = array();

		if(isset(self::$accessList[$controller])){

			if(!empty(self::$access[$controller])){

				if(isset(self::$accessList["$controller-$action"])){

					if(!empty(self::$access["$controller-$action"])){
						return true;
					}else {
						return false;
					}

				}

				return true;

			}

			return false;

		}
		return true;
	}


	public static function postToLinearAccess($post){

		self::getAccess();
		self::getAccessList();

		return Zend_Json_Encoder::encode(FRM_Tools_Array::setAccessArrayFromTree($post, self::$accessTree));
	}

	public static function getFilteredMenu($menu){

		self::getAccess();
		self::getAccessList();
		return FRM_Tools_Array::filterAccessTree($menu, self::$access);
	}
}